package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsDLTranOutQueryCmd;
import com.jackrain.nea.fc.dl.mapper.WmsDLTranMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 提交时触发/orig 发货店仓WMS管控
 *
 * @author xuxinshuai
 * @date 2018/05/05
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsDLTranOutQueryCmdImpl extends CommandAdapter implements WmsDLTranOutQueryCmd {


    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Autowired
    QueryCpUtil postQueryEvemt;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        ValueHolder vh = new ValueHolder();
        WmsDLTranMapper wmsDLTranMapper = ApplicationContextHandle.getBean(WmsDLTranMapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("WmsDLTranOutQueryCmdImpl-->param-->{}",param);

        if (null == param || (!param.containsKey("IDS")) || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
        JSONArray dataArray = param.getJSONArray("IDS");
        JSONArray fixArray = new JSONArray();
        StringBuffer messageOne = new StringBuffer("入库通知单WMS查询，数据为空-->>");
        StringBuffer messageTwo = new StringBuffer("当前单据为未提交状态，不允许传入WMS-->>");
        StringBuffer message = new StringBuffer("对应发货店仓不是WMS管控!-->>");
        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject fixcolumn = new JSONObject();
            String idStr = dataArray.getString(i);
            HashMap mainMap = wmsDLTranMapper.selectwmstranoutsql(idStr);
            if (mainMap == null) {
//                log.debug("入库通知单WMS查询，数据为空，idStr="+idStr);
                messageOne.append(idStr);
                continue;
            }
            JSONObject mainJo = new JSONObject(mainMap);
            String sendstatus = mainJo.getString("STATUS");
            if (!"2".equals(sendstatus)) {
//                log.debug("当前单据为未提交状态，不允许传入WMS！");
                messageTwo.append(mainJo.getString("bill_no")+",");
                continue;
            }
            mainJo.remove("STATUS");
            //跨库查询
            String storeStr = mainJo.getString("orig_ecode");
            if (null != storeStr) {

                JSONObject whereJo = new JSONObject();
                whereJo.put("ECODE", storeStr);
                JSONObject result = postQueryEvemt.queryCP("CP_C_STORE", "ISWMS,WMS_STORE_ECODE", whereJo);
                if (result != null) {
                    String iswms = TypeUtils.castToString(result.getString("ISWMS"));
                    if (!"1".equals(iswms)) {
                        message.append(mainJo.getString("bill_no")+",");
                        continue;
                    }
                    String wmsecode = TypeUtils.castToString(result.getString("WMS_STORE_ECODE"));
                    mainJo.put("wms_store_code", wmsecode);
                }
            }
            //跨库查询
            String storeDestStr = mainJo.getString("dest_ecode");
            if (null != storeDestStr) {

                JSONObject whereJo = new JSONObject();
                whereJo.put("ECODE", storeDestStr);
                JSONObject result = postQueryEvemt.queryCP("CP_C_STORE", "LOGISTICS", whereJo);
                try {
                    if (result != null) {
                        String logistics_batch = result.getString("LOGISTICS");
                        mainJo.put("logistics_batch", logistics_batch);
                    } else {
                        mainJo.put("logistics_batch", "0");
                    }
                } catch (Exception e) {
                    mainJo.put("logistics_batch", "0");
                }

            } else {
                mainJo.put("logistics_batch", "0");
            }
            fixcolumn.put("mainData", mainJo);
            //查询子表
            List<HashMap> mapList = wmsDLTranMapper.selectwmstranouttimesql(idStr);
            JSONArray jsonArray = new JSONArray();
            for (HashMap hashMap : mapList) {

                JSONObject jsonObject = new JSONObject(hashMap);
                jsonObject.put("bill_no", mainJo.getString("bill_no"));
                jsonArray.add(jsonObject);
            }
            fixcolumn.put("itemData", jsonArray);
            fixArray.add(fixcolumn);

        }
        messageTwo.deleteCharAt(messageTwo.length()-1);
        message.deleteCharAt(message.length()-1);
        vh.put("data", fixArray);
        vh.put("code", 0);
        vh.put("message", "查询成功->"+messageOne.append(messageTwo).append(message));
        return vh;

    }

    /**
     * list TO jsonarray
     *
     * @param mapList
     * @return jsonArray
     */
    public JSONArray listToJsonarray(List<HashMap> mapList) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < mapList.size(); i++) {
            HashMap map = (HashMap) mapList.get(i);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
            jsonArray.add(param);
        }
        return jsonArray;
    }

    /**
     * str TO Date
     *
     * @param str
     * @return Date
     */
    public Date stringToDate(String str) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟
        Date mdate = null;
        try {
            mdate = sdf.parse(str);

        } catch (Exception e) {
            throw new NDSException(e.getMessage());
        }
        return mdate;
    }
}